<template>
  <div class="mapWrapper">
    <a-button type="primary" @click="goBack">返回上级</a-button>
    <div class="level-info">当前层级: {{ currentLevel }} - {{ currentMapName }}</div>
    <div ref="mapChartRef" style="height: 100%; width: 100%"></div>
  </div>
</template>

<script setup>
import axios from "axios";
import {ref, onMounted, computed} from "vue";
import * as echarts from "echarts";

const mapChartRef = ref();
const initChinaMap = ref();
const initAdCode = ref(100000); // 默认中国地图编码
const currentMapName = ref("中国");
const currentLevel = ref("国家");
const mapList = ref([]);
const historyInfo = ref([]);

// 高德地图API密钥 - 实际使用时请替换为您的有效密钥
const aMapKey = "0e344a4c3c2d7fe15047a127053128f1";

// 散点数据（标注重点城市）
const points = ref([
  {name: '北京朝阳区', value: [116.48641, 39.92149], itemStyle: {color: '#A6283F'}},
  {name: '沧州任丘市', value: [116.0983, 38.7072], itemStyle: {color: '#00EEFF'}}
])

// 飞线数据（包含新增的朝阳->任丘）
const linesData = ref([
  {
    coords: [
      [116.48641, 39.92149], // 北京朝阳区
      [116.0983, 38.7072]     // 沧州任丘市
    ],
    lineStyle: {
      color: "#FF4500",       // 橙色高亮线条
      width: 2,
      type: 'solid'           // 实线
    }
  }
])

// 飞机路径SVG（用于飞线动画）
const planePath = ref('path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z')

// 创建占位地图数据（当无法获取实际数据时使用）
const createPlaceholderMap = (name, code) => {
  console.log(`使用占位数据创建 ${name} 地图`);

  // 根据行政级别设置当前层级
  if (code === 100000) {
    currentLevel.value = "国家";
  } else if (code.toString().length === 2) {
    currentLevel.value = "省份";
  } else if (code.toString().length === 4) {
    currentLevel.value = "城市";
  } else if (code.toString().length === 6) {
    currentLevel.value = "县";
  }

  // 创建简单的矩形区域
  // 对于县级以下区域，根据名称创建不同的子区域
  if (code.toString().length === 6) {
    // 如果是县级区域，创建几个模拟的乡镇
    const townFeatures = [
      createFeature(`${name}镇`, `${code}01`, [116.1, 38.7]),
      createFeature(`${name}东部`, `${code}02`, [116.15, 38.7]),
      createFeature(`${name}西部`, `${code}03`, [116.05, 38.7]),
      createFeature(`${name}南部`, `${code}04`, [116.1, 38.65]),
      createFeature(`${name}北部`, `${code}05`, [116.1, 38.75])
    ];

    const geoJSON = {
      type: "FeatureCollection",
      features: townFeatures
    };

    mapList.value = townFeatures.map(item => item.properties);
    renderChart(name, geoJSON);
    currentLevel.value = "乡镇";
  } else {
    // 创建一个简单的区域
    const geoJSON = {
      type: "FeatureCollection",
      features: [
        createFeature(name, code, [116.1, 38.7])
      ]
    };

    mapList.value = [geoJSON.features[0].properties];
    renderChart(name, geoJSON);
  }
};

// 创建GeoJSON要素
const createFeature = (name, adcode, center) => {
  const offsetLng = 0.03;
  const offsetLat = 0.03;

  return {
    type: "Feature",
    properties: {
      name: name,
      adcode: adcode,
      center: center,
      childrenNum: adcode.toString().length >= 8 ? 0 : 5
    },
    geometry: {
      type: "Polygon",
      coordinates: [[
        [center[0] - offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] - offsetLat]
      ]]
    }
  };
};

// 从高德地图获取行政区域数据
const getAMapDistrictData = async (adcode) => {
  try {
    // 使用高德地图行政区域查询API - 可以使用adcode或地区名称
    const url = `https://restapi.amap.com/v3/config/district?keywords=${adcode}&subdistrict=1&key=${aMapKey}&extensions=all`;
    console.log("请求高德API:", url);
    const response = await axios.get(url);

    if (response.data.status === '1' && response.data.districts && response.data.districts.length > 0) {
      const district = response.data.districts[0];
      console.log("获取到高德地图数据:", district.name, "下级区域数量:", district.districts ? district.districts.length : 0);

      // 返回街道/乡镇级数据
      if (district.districts && district.districts.length > 0) {
        return district.districts;
      }
    }
    return null;
  } catch (error) {
    console.error("获取高德地图数据失败:", error);
    return null;
  }
};

// 将高德地图数据转换为GeoJSON格式
const convertToGeoJSON = (districts) => {
  if (!districts || districts.length === 0) return null;

  const features = districts.map(district => {
    // 解析中心点坐标
    const centerStr = district.center;
    const centerParts = centerStr ? centerStr.split(',') : [116, 39];
    const center = [parseFloat(centerParts[0]), parseFloat(centerParts[1])];

    // 使用多边形数据（如果存在）或创建简单的矩形
    let polygonCoordinates = [];

    // 检查是否有多边形数据
    if (district.polyline) {
      try {
        // 解析多边形字符串
        const polylineParts = district.polyline.split(';');

        for (const part of polylineParts) {
          const points = part.split(',').map(p => parseFloat(p));
          const coordinates = [];

          // 将扁平的坐标数组转换为[经度,纬度]对
          for (let i = 0; i < points.length; i += 2) {
            if (i + 1 < points.length) {
              coordinates.push([points[i], points[i + 1]]);
            }
          }

          if (coordinates.length > 2) {
            // 确保多边形闭合
            if (coordinates[0][0] !== coordinates[coordinates.length - 1][0] ||
                coordinates[0][1] !== coordinates[coordinates.length - 1][1]) {
              coordinates.push([coordinates[0][0], coordinates[0][1]]);
            }

            polygonCoordinates.push(coordinates);
          }
        }
      } catch (e) {
        console.error("解析多边形数据失败:", e);
        // 出错时使用默认矩形
        const offsetLat = 0.02;
        const offsetLng = 0.02;

        polygonCoordinates = [[
          [center[0] - offsetLng, center[1] - offsetLat],
          [center[0] + offsetLng, center[1] - offsetLat],
          [center[0] + offsetLng, center[1] + offsetLat],
          [center[0] - offsetLng, center[1] + offsetLat],
          [center[0] - offsetLng, center[1] - offsetLat]
        ]];
      }
    } else {
      // 没有多边形数据时创建简单矩形
      const offsetLat = 0.02;
      const offsetLng = 0.02;

      polygonCoordinates = [[
        [center[0] - offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] - offsetLat]
      ]];
    }

    // 如果没有有效的多边形，创建一个默认矩形
    if (polygonCoordinates.length === 0) {
      const offsetLat = 0.02;
      const offsetLng = 0.02;

      polygonCoordinates = [[
        [center[0] - offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] - offsetLat],
        [center[0] + offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] + offsetLat],
        [center[0] - offsetLng, center[1] - offsetLat]
      ]];
    }

    return {
      type: "Feature",
      properties: {
        name: district.name,
        adcode: district.adcode,
        center: center,
        level: "township",
        childrenNum: 0,
        parent: {adcode: district.citycode || district.adcode.substring(0, 4)}
      },
      geometry: {
        type: "Polygon",
        coordinates: polygonCoordinates
      }
    };
  });

  return {
    type: "FeatureCollection",
    features: features
  };
};

// 获取地图数据 - 增强版
const getMapData = async (code) => {
  try {
    // 如果是县级代码，并且希望继续下钻
    if (code.toString().length === 6 && currentLevel.value === "县") {
      try {
        // 获取乡镇数据
        const townshipData = await getAMapDistrictData(code);

        if (townshipData && townshipData.length > 0) {
          currentLevel.value = "乡镇";

          // 转换为GeoJSON格式
          const geoJSONData = convertToGeoJSON(townshipData);

          if (geoJSONData) {
            mapList.value = geoJSONData.features.map(item => item.properties);
            renderChart(currentMapName.value, geoJSONData);
            return;
          }
        }
      } catch (error) {
        console.error("高德API获取乡镇数据失败:", error);
      }

      // 如果高德API获取失败或没有数据，使用占位数据
      console.log("无法获取乡镇级数据，使用占位数据");
      return createPlaceholderMap(currentMapName.value, code);
    }

    // 获取阿里云地图数据（县级及以上）
    // 尝试两种可能的URL格式，增加健壮性
    let response;
    try {
      // 首先尝试不带_full的URL
      response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${code}.json`);
    } catch (error) {
      try {
        // 如果失败，尝试带_full的URL
        response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${code}_full.json`);
      } catch (innerError) {
        console.error("无法获取阿里云地图数据:", innerError);
        // 创建一个简单的占位地图数据
        return createPlaceholderMap(currentMapName.value, code);
      }
    }

    if (response && response.status === 200) {
      // 设置当前层级名称
      if (code === 100000) {
        currentLevel.value = "国家";
      } else if (code.toString().length === 2) {
        currentLevel.value = "省份";
      } else if (code.toString().length === 4) {
        currentLevel.value = "城市";
      } else if (code.toString().length === 6) {
        currentLevel.value = "县";
      }

      mapList.value = [];
      response.data.features.forEach((item) => {
        mapList.value.push(item.properties);
      });

      renderChart(currentMapName.value, response.data);
    }
  } catch (error) {
    console.error("获取地图数据整体失败:", error);
    // 最后的兜底方案
    createPlaceholderMap(currentMapName.value, code);
  }
};

// 渲染地图
const renderChart = (mapName, mapData) => {
  echarts.registerMap(mapName, mapData);

  const option = {
    tooltip: {
      show: true,
      trigger: "item",
      backgroundColor: "#0C121C",
      borderColor: "rgba(0, 0, 0, 0.16)",
      textStyle: {color: "#DADADA"},
      formatter: "{b}"
    },
    // 使用单一的地图实例，将所有图层放在同一个坐标系下
    geo: {
      map: mapName,
      roam: false,  // 禁用缩放平移
      zoom: 1.1,
      label: {
        show: true,
        fontSize: 12,
        color: '#000'
      },
      itemStyle: {
        borderColor: "#F59A23",
        areaColor: "#E6E6FA"  // 浅紫色地图底色
      },
      emphasis: {
        itemStyle: {
          areaColor: "#CCEBEB",
          borderColor: "#34AEAE"
        }
      }
    },
    series: [
      // 使用单一地图系列，并将需要的所有数据放在一起
      {
        name: "区域地图",
        type: "map",
        map: mapName,
        roam: false,  // 禁用缩放和平移
        zoom: 1.1,
        // 确保和geo配置使用相同的样式
        itemStyle: {
          borderColor: "#F59A23",
          areaColor: "#E6E6FA"
        },
        emphasis: {
          itemStyle: {
            areaColor: "#CCEBEB",
            borderColor: "#34AEAE"
          }
        },
        label: {
          show: true,
          fontSize: 12
        },
        // 地图数据放这里
        data: []
      },
      // 飞线层 - 确保它和地图使用相同的geoIndex
      {
        name: "飞线",
        type: "lines",
        // 使用相同的地图坐标系
        coordinateSystem: "geo",
        // 保持高z轴层级
        zlevel: 2,
        effect: {
          show: true,
          period: 4,
          trailLength: 0.02,
          symbol: planePath.value,
          symbolSize: 15
        },
        lineStyle: {
          color: "#FF4500",
          width: 1,
          opacity: 0.8,
          curveness: 0.3
        },
        data: linesData.value
      },
      // 散点层 - 同样确保它和地图使用相同的geoIndex
      {
        name: "标注点",
        type: "scatter",
        // 使用相同的地图坐标系
        coordinateSystem: "geo",
        // 保持高z轴层级
        zlevel: 3,
        symbol: "pin",
        symbolSize: [40, 50],
        label: {
          show: true,
          position: "right",
          fontSize: 14,
          color: "#333",
          formatter: "{b}"
        },
        itemStyle: {
          color: "#D8BC37"
        },
        data: points.value
      }
    ]
  };

  initChinaMap.value.setOption(option, true);  // 使用true参数完全替换配置

  // 地图点击下钻
  initChinaMap.value.off("click");
  initChinaMap.value.on("click", (params) => {
    console.log("点击地图:", params);
    // 仅对地图区域点击有效
    if ((params.componentType === 'geo' || params.seriesType === 'map') && params.name) {
      console.log("有效点击，查找区域:", params.name);
      console.log("当前区域列表:", mapList.value.map(item => item.name));

      const activeItem = mapList.value.find((item) => item.name === params.name);
      console.log("找到的区域项:", activeItem);

      if (activeItem) {
        // 将当前级别信息保存到历史记录
        historyInfo.value.push({
          name: currentMapName.value,
          adcode: activeItem.adcode || (activeItem.parent ? activeItem.parent.adcode : initAdCode.value),
          level: currentLevel.value
        });

        // 更新当前地图名称
        currentMapName.value = params.name;

        // 根据行政级别代码获取新的地图数据
        if (activeItem.adcode) {
          console.log("获取下钻数据，adcode:", activeItem.adcode);
          getMapData(activeItem.adcode);
        } else if (activeItem.parent && activeItem.parent.adcode) {
          // 使用父级代码作为备选
          console.log("使用父级adcode:", activeItem.parent.adcode);
          getMapData(activeItem.parent.adcode);
        }
      } else {
        console.log("未找到匹配区域");
      }
    }
  });

  // 飞线点击事件
  initChinaMap.value.on("click", {seriesType: "lines"}, (params) => {
    console.log("点击飞线:", params);
  });
};

// 初始化
onMounted(() => {
  initChinaMap.value = echarts.init(mapChartRef.value);
  getMapData(initAdCode.value);

  console.log("初始化地图，加载全国数据");

  // 由于禁用了缩放和拖拽，我们仍保留窗口大小改变的事件
  // 以确保地图在容器大小变化时能正确显示
  window.addEventListener('resize', () => {
    if (initChinaMap.value) {
      initChinaMap.value.resize();
    }
  });
});

// 返回上级
const goBack = () => {
  console.log("返回上级, 当前历史:", historyInfo.value);

  if (historyInfo.value.length > 0) {
    // 获取上一级的信息
    const previousLevel = historyInfo.value.pop();
    currentMapName.value = previousLevel.name;
    currentLevel.value = previousLevel.level;

    console.log("返回到:", previousLevel.name, previousLevel.adcode);

    // 获取上一级的地图数据
    getMapData(previousLevel.adcode);
  } else {
    // 返回到全国
    currentMapName.value = "中国";
    currentLevel.value = "国家";
    console.log("返回到全国");
    getMapData(initAdCode.value);
  }
};
</script>

<style scoped>
.mapWrapper {
  width: 1000px;
  height: 800px;
  padding: 20px;
  background: #f0f2f5;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.level-info {
  margin-bottom: 10px;
  font-size: 14px;
  color: #1890ff;
  font-weight: bold;
}

/* 按钮样式增强 */
.ant-btn-primary {
  margin-bottom: 15px;
  background: #1890ff;
  border-color: #1890ff;
}
</style>